package com.mxy.myapplication2.java;

import android.animation.Animator;
import android.animation.AnimatorListenerAdapter;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.os.Process;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.view.ViewAnimationUtils;
import android.view.ViewStub;

import com.mxy.myapplication2.R;
import com.mxy.myapplication2.kotlin.MyFirstKotlinActivity;
import com.mxy.myapplication2.kotlin.SocketClientActivity;
import com.mxy.myapplication2.kotlin.SocketServerActivity;
import com.mxy.myapplication2.util.JNIUtil;

import org.greenrobot.eventbus.EventBus;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;

/**
 * @author 马晓勇
 */
public class FirstActivity extends AppCompatActivity implements View.OnClickListener {

    private static final String TAG = "MXY";
    private View rootView;
    private Animator animator;
    private View imageView;
    private ViewStub viewStub;
    private CusTextView custTvViewSub;
    private CusTextView cusTv;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        Log.w("MXY", "activity onCreate()");
        setContentView(R.layout.activity_first);

        rootView = findViewById(R.id.rootView);
        cusTv = findViewById(R.id.cusTv);
        imageView = findViewById(R.id.imageView);
        // android 5.0以上控件的 ripple点击效果
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            imageView.setBackgroundResource(R.drawable.ripple_bg);
        } else {
            imageView.setBackgroundResource(android.R.color.holo_orange_dark);
        }
        imageView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                // 只能执行一次inflate(),重复执行会抛异常
                if (custTvViewSub == null) {
                    custTvViewSub = (CusTextView) viewStub.inflate();
                }
            }
        });
        viewStub = findViewById(R.id.viewStub);
        findViewById(R.id.button).setOnClickListener(this);
        findViewById(R.id.serializable).setOnClickListener(this);
        findViewById(R.id.buttonForKotlin).setOnClickListener(this);
        findViewById(R.id.openSocketServerPage).setOnClickListener(this);
        findViewById(R.id.openSocketClientPage).setOnClickListener(this);
        findViewById(R.id.viewFlipperAndEventBusTestbtn).setOnClickListener(this);

        // 进程号
        Log.i(TAG, "myPid: " + Process.myPid());
        // 当前线程号
        Log.i(TAG, "myTid: " + Process.myTid());
        // 当前调用该应用程序的用户号 = 7
        Log.i(TAG, "myUid: " + Process.myUid());
        // 当前线程ID
        Log.i(TAG, "currentThreadId: " + Thread.currentThread().getId());
        // 主线程ID
        Log.i(TAG, "mainThreadId: " + getMainLooper().getThread().getId());
        // 当前Activity所在栈的ID
        Log.i(TAG, "ActivityTaskId: " + getTaskId());
        // 当前调用该应用程序的用户号 = 3
        Log.i(TAG, "ApplicationUid: " + getApplicationInfo().uid);
        // 当前调用该应用程序的进程名
        Log.i(TAG, "ApplicationProcessName: " + getApplicationInfo().processName);


        // 通过manifest中配置的meta_data获取gradle中的配置的实际渠道属性信息
        String url = Util.getAppMetaData(getApplication(), "InterFaceURL");
        String channel = Util.getAppMetaData(getApplication(), "APP_CHANNEL");
        Util.showToast(this, url + channel);



        cusTv.post(new Runnable() {
            @Override
            public void run() {
                // 1.activity onesume()
                // 2.view的onMesure()
                // 3.view的layout()
                // 4.view的onDraw()
                // 再执行Runnable(主线程)
                Log.w("MXY", "custTv.post()");
            }
        });


        new Handler() {
        }.post(new Runnable() {
            @Override
            public void run() {
                // activity onResoume()之后执行
                Log.w("MXY", "new Handler.post()");
            }
        });



        new Thread(new Runnable() {
            @Override
            public void run() {
                // 在异步线程中创建一个handler的化，要么使用已经运行了start的looper，比如MainLooper
                // 或者自己创建的HandlerThred，并执行了start()
                // 或者在线程中调用Looper.prepare();
                // handler会默认使用创建该对象的线程的looper，如果当前线程的looper没有调用prepare()
                // 那么就无法完成messageQuene的轮询工作，就会抛异常。
                Looper.prepare();
                Handler handler = new Handler();
            }
        }){}.start();
    }

    @Override
    public void onAttachedToWindow() {
        super.onAttachedToWindow();
        // 在onResume()之后执行
        Log.w("MXY", "activity onAttachedToWindow");
    }

    @Override
    protected void onResume() {
        super.onResume();
        Log.w("MXY", "activity onResume()");
    }

    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);
        System.out.println("FirstActivity_onNewIntent");
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        System.out.println("FirstActivity_onActivityResult");
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.serializable:
//                deepCopyObjWithStream();

                final Person p1 = new Person("小浩浩", 38);
                final Person p2 = new Person("小浩浩", 38);

                // 测试并发锁作用域
                // 结论:ReentrantLockde的作用域与synchronized相同(对象/类)
                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        p1.testLockA(FirstActivity.this);
                    }
                }).start();

                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        p2.testLockB(FirstActivity.this);
                    }
                }).start();

                break;
            case R.id.button:
//                startActivityForResult(new Intent(this, SecondActivity.class), 1);
                if (animator != null && !animator.isStarted()) {
                    animator.start();
                } else {
                    startActivity(new Intent(FirstActivity.this, CustomizedRefreshExampleActivity.class));
                }
                Util.showToast(this, JNIUtil.getText());
                break;
            case R.id.buttonForKotlin:
                startActivity(new Intent(FirstActivity.this, MyFirstKotlinActivity.class));
                break;
            case R.id.openSocketServerPage:
                startActivity(new Intent(this, SocketServerActivity.class));
                break;
            case R.id.openSocketClientPage:
                startActivity(new Intent(this, SocketClientActivity.class));
                break;
            case R.id.viewFlipperAndEventBusTestbtn:
                Intent intent = new Intent("ViewFlipperAndEventBusTest");
                intent.addCategory(Intent.CATEGORY_DEFAULT);
                startActivity(intent);
                EventBus.getDefault().removeAllStickyEvents();
                EventBus.getDefault().postSticky(new Person("土豪浩", 50));
                //越后发越先响应
                EventBus.getDefault().postSticky(new Pojo());
                break;
            default:
                break;
        }
    }


    /**
     * 使用序列化特性对对象进行深拷贝
     * 不写入文件方式
     * {#}
     */
    private void deepCopyObjWithStream() {

        Person p = new Person("小浩浩", 38);
        try {
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            ObjectOutputStream oos = new ObjectOutputStream(baos);
            oos.writeObject(p);

            p = null;

            // 从流中读出对象
            ByteArrayInputStream bais = new ByteArrayInputStream(baos.toByteArray());
            ObjectInputStream ois = new ObjectInputStream(bais);
            p = (Person) ois.readObject();

            ois.close();
            oos.close();

            System.out.println(p.goodsNums.get(0).name);
            System.out.println(p.goodsNums.get(0).age);
            System.out.println(p.sex);

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    public void onDetachedFromWindow() {
        super.onDetachedFromWindow();
        // 在onDestory()之后执行
        Log.w("MXY", "activity onDetachedFromWindow");
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        Log.w("MXY", "activity onDestory()");
    }

    @Override
    public void onWindowFocusChanged(boolean hasFocus) {
        super.onWindowFocusChanged(hasFocus);
        Log.w("MXY", "activity onWindowFocusChanged = " + hasFocus);
        if (animator == null && hasFocus) {
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
                float endRadius = (float) Math.hypot(rootView.getWidth(), rootView.getHeight());
                animator = ViewAnimationUtils.createCircularReveal(rootView, 0, 0, 0, endRadius);
                animator.setDuration(1000);
                animator.addListener(new AnimatorListenerAdapter() {
                    @Override
                    public void onAnimationEnd(Animator animation) {
                        super.onAnimationEnd(animation);
                        animator = null;
                        startActivity(new Intent(FirstActivity.this, CustomizedRefreshExampleActivity.class));
                    }
                });
            }
        }
    }
}